# 编译器和选项
CXX = g++
CXXFLAGS = -Iinclude -I/usr/include/eigen3 -std=c++17
LDFLAGS = -lblas -llapack

PY = python3

# 源文件和目标
SRC = src/main.cpp src/MultigridSolver.cpp src/Grid.cpp src/BoundaryConditions.cpp src/Function.cpp
OBJ = $(SRC:.cpp=.o)
EXEC = poisson_solver

# 文档相关
OBJ_TEX = $(wildcard doc/*.tex)
NAME_TEX = $(OBJ_TEX:doc/%.tex=%.tex)

# Python脚本
SRC_PY = $(wildcard src/*.py)
TARGETS_PY = $(SRC_PY)

# 修配置文件路径为input目录
CONFIGS := $(wildcard input/*.json)
CONFIG_NAMES := $(notdir $(CONFIGS:.json=))

# 默认目标改为显示帮助
all: help

# 运行目标指向input目录
run-%: $(EXEC)
	@if [ -f "input/$*.json" ]; then \
		echo "Running with input/$*.json..."; \
		./$(EXEC) input/$*.json; \
		echo "Running Python script for plotting..."; \
		$(PY) $(SRC_PY); \
	else \
		echo "Error: input/$*.json not found"; \
		echo "Available configs: $(CONFIG_NAMES)"; \
		exit 1; \
	fi

# 帮助信息
help:
	@echo "Usage: make run-<config>"
	@echo "Available configurations in input/:" 
	@for conf in $(CONFIG_NAMES); do \
		echo "  $$conf"; \
	done
	@echo ""
	@echo "Example: make run-test1"
	@echo ""
	@echo "Other targets:"
	@echo "  make doc    - Generate documentation"
	@echo "  make clean  - Clean build files"

$(EXEC): $(OBJ)
	$(CXX) $(CXXFLAGS) -o $@ $^ $(LDFLAGS)

src/%.o: src/%.cpp
	$(CXX) $(CXXFLAGS) -c $< -o $@

doc: $(OBJ_TEX)
	@cd doc; \
	for texname in $(NAME_TEX); do \
		echo "Processing $$texname..."; \
		xelatex $$texname; \
		bibtex $(basename $$texname .tex).aux; \
		xelatex $$texname; \
		xelatex $$texname; \
	done

clean:
	rm -f $(OBJ) $(EXEC)
	cd doc && rm -f *.aux *.bbl *.blg *.log *.run.xml *.out *.synctex.gz *.csv main.bbl main-blx.bib
	rm -rf src/build

.PHONY: all run-% help doc clean